package com.kyzh.core.pager.weal.live

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.gushenge.core.beans.GiftUserInfo
import com.gushenge.core.beans.LiveRoomInfo
import com.gushenge.core.beans.RoomGift
import com.gushenge.core.dao.MMKVConsts
import com.jeremyliao.liveeventbus.LiveEventBus
import com.kyzh.core.R
import com.kyzh.core.pager.gamedetail.GameDetailActivity1
import com.kyzh.core.databinding.FragmentLivechatBinding
import com.kyzh.core.databinding.ItemGroupchatMsgBinding
import com.kyzh.core.dialog.showLiveRoomManagerDialog
import com.kyzh.core.dialog.showSendGiftDialog
import com.kyzh.core.dialog.showSendMessageDialog
import com.kyzh.core.pager.weal.live.adapter.LiveChatAdapter
import com.kyzh.core.pager.weal.live.msgbean.MsgEntity
import com.kyzh.core.utils.im.TUIUtils
import com.gushenge.core.toast
import com.kyzh.core.utils.setVisibility
import com.tencent.imsdk.v2.*
import com.tencent.qcloud.tuicore.component.fragments.BaseFragment
import org.jetbrains.anko.backgroundResource
import org.jetbrains.anko.support.v4.runOnUiThread

class LiveChatFragment :BaseFragment() {
    companion object{
        fun newInstance(data1 : LiveRoomInfo): LiveChatFragment {
            val args = Bundle()
            args.putSerializable("LiveRoomInfo",data1)
            val fragment = LiveChatFragment()
            fragment.arguments = args
            return fragment
        }
    }
    // 直播数据
    private var liveRoomInfo : LiveRoomInfo? = null
    private var bind:FragmentLivechatBinding? = null
    private var groupChatListener: VoiceRoomSimpleListener? = null
    // 群聊内容得
    private var adapter : LiveChatAdapter = LiveChatAdapter()
    init {
        groupChatListener = VoiceRoomSimpleListener()
    }
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        bind = FragmentLivechatBinding.inflate(inflater)
        bind?.lifecycleOwner = requireActivity()
        bind?.proxy = Proxy()
        return bind?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        liveRoomInfo = arguments?.getSerializable("LiveRoomInfo") as LiveRoomInfo?
        initChat()
        initGame()
    }
    //游戏展示
    fun initGame(){
        if(liveRoomInfo?.game==null ||liveRoomInfo?.game?.id==null){
            bind?.itemGame?.root?.setVisibility(false)
            return
        }
        bind?.itemGame?.data = liveRoomInfo?.game
        bind?.itemGame?.tvType ?.text =liveRoomInfo?.game?.tuijianzhishu.toString() + "  "+  liveRoomInfo?.game?.type
        // 处理下错误  避免服务器传错误得数据导致崩溃  !!用了！！
        kotlin.runCatching {
            bind?.itemGame?.rb?.rating = liveRoomInfo?.game?.point!!.toFloat()
            bind?.itemGame?.rb?.isEnabled = false
            bind?.itemGame?.tvDown?.text = "下载主播\n" +
                    "同款游戏"
            bind?.itemGame?.tvDown?.backgroundResource = R.drawable.bg_border_white_radius_4dp
            bind?.itemGame?.tvDown?.setOnClickListener {

                GameDetailActivity1.start(requireContext(),liveRoomInfo?.game?.id!!)
            }
        }
    }

    // 处理聊天区域问题
    fun initChat(){
        //先进入群聊
        joinGroup()
        V2TIMManager.getInstance().joinGroup(liveRoomInfo?.room_id,"",object : V2TIMCallback{
            override fun onSuccess() {
                Log.e(TUIUtils.TAGQUN, "onSuccess: ")
                V2TIMManager.getInstance().addSimpleMsgListener(groupChatListener)
            }
            override fun onError(p0: Int, p1: String?) {
                Log.e(TUIUtils.TAGQUN, "onError:  $p0   $p1")
                runOnUiThread {
                    "进入失败，请重试".toast()
//                    requireActivity().finish()
                }
            }
        })
        // 消息监听

        bind?.revChat?.adapter = adapter
        // 顶部公告
        val header = ItemGroupchatMsgBinding.inflate(layoutInflater)
        header.tvMsg.setTextColor(resources.getColor(R.color.font_99))
        header.tvMsg.text = "${liveRoomInfo?.text}"
        adapter.addHeaderView(header.root)
    }
    //发送消息
    fun senMsg(msg:String,listener : ()->Unit){
        // 发送群聊消息
        V2TIMManager.getInstance().sendGroupTextMessage(msg, liveRoomInfo?.room_id,
            V2TIMMessage.V2TIM_PRIORITY_NORMAL,object : V2TIMValueCallback<V2TIMMessage>{
                override fun onSuccess(success: V2TIMMessage?) {listener.invoke()  }
                override fun onError(p0: Int, p1: String?) {
                    Log.e(TUIUtils.TAGQUN, "senMsg ERROR :    CODE $p0   MSG $p1")
                    runOnUiThread {
                        "消息发送失败".toast()
                    }
                }
            })
    }

    //  进群通知
    fun joinGroup(){
        V2TIMManager.getInstance().addGroupListener(object :V2TIMGroupListener(){
            override fun onMemberEnter(
                groupID: String?,
                memberList: MutableList<V2TIMGroupMemberInfo>?
            ) {
                memberList?.forEach {
                    val msgEntity = MsgEntity()
                    msgEntity.userId = it.userID
                    msgEntity.userName = it.nickName
                    msgEntity.content = "加入直播间"
                    msgEntity.userIcon = it.faceUrl
                    msgEntity.type = MsgEntity.TYPE_JOIN
                    adapter.addData( msgEntity)
                    bind?.revChat?.scrollToPosition(adapter.getItemCount() - 1);
                }
            }

            override fun onGroupDismissed(groupID: String?, opUser: V2TIMGroupMemberInfo?) {
                super.onGroupDismissed(groupID, opUser)
                requireActivity().finish()
            }
        }


        )

    }

    private inner class VoiceRoomSimpleListener : V2TIMSimpleMsgListener() {
        //文本消息
        override fun onRecvGroupTextMessage(
            msgID: String,
            groupID: String,
            sender: V2TIMGroupMemberInfo,
            text: String
        ) {

            Log.e( TUIUtils.TAGQUN, "onRecvGroupTextMessage  im get text msg group:" + groupID + " userid :" + sender.userID + " text:" + text )
            if (groupID != liveRoomInfo?.room_id) {
                return
            }
            //           0         1   2                  3   4
            // 礼物规则  playwith#gift#type(1 gif 2 SVGA)#url#时间  playwith#giftName#送
            //playwith#gift#${gift.img_type}#${if (gift.img_type == "0") gift.icon else gift.img}#${gift.time}
            if (text.startsWith(MsgEntity.TYPE_GIFT)){
                if(text.startsWith("playwith#giftName#送")){
                    kotlin.runCatching {
                        val spGift = text.split("#")
                        val msgEntity = MsgEntity()
                        msgEntity.userId = sender.userID
                        msgEntity.userName = sender.nickName
                        msgEntity.content = spGift[2]
                        msgEntity.userIcon = sender.faceUrl
                        msgEntity.type = MsgEntity.TYPE_NORMAL
                        adapter.addData( msgEntity)
                        bind?.revChat?.scrollToPosition(adapter.getItemCount() - 1);
                    }
                }else{
                    kotlin.runCatching {
                        val spGift = text.split("#")
                        val roomGift = RoomGift().apply {
                            img_type = spGift[2]
                            icon =  spGift[3]
                            img = spGift[3]
                            time = spGift[4].toInt()
                        }
                        LiveEventBus.get<RoomGift>("RoomGift").post(roomGift)
                    }
                }

            }else{
                val msgEntity = MsgEntity()
                msgEntity.userId = sender.userID
                msgEntity.userName = sender.nickName
                msgEntity.content = text
                msgEntity.userIcon = sender.faceUrl
                msgEntity.type = MsgEntity.TYPE_NORMAL
                adapter.addData( msgEntity)
                bind?.revChat?.scrollToPosition(adapter.getItemCount() - 1);
            }
        }
        //信令消息
        override fun onRecvGroupCustomMessage(
            msgID: String,
            groupID: String,
            sender: V2TIMGroupMemberInfo,
            customData: ByteArray
        ) {
            if (groupID != liveRoomInfo?.room_id) {
                return
            }
            val customStr = String(customData)
            val close = "{\"type\":\"close\"}"
            Log.e(  TUIUtils.TAGQUN, "onRecvGroupCustomMessage  im get text msg group:" + groupID + " userid :" + sender.userID + " msgID:" + msgID  + "customData"+ customStr    )
            if(close==customStr){
                // 发送关闭指令  activity 来处理逻辑
                LiveEventBus.get<Int>("closeRoom").post(1)
            }else{
                val msgEntity = MsgEntity()
                msgEntity.userId = sender.userID
                msgEntity.userName = sender.nickName
                msgEntity.content = customStr
                msgEntity.userIcon = sender.faceUrl
                msgEntity.type = MsgEntity.TYPE_NORMAL
                adapter.addData( msgEntity)
                bind?.revChat?.scrollToPosition(adapter.getItemCount() - 1);
            }


        }
    }
    var  users:ArrayList<GiftUserInfo> = arrayListOf()
    inner class Proxy{
        //发消息
        fun senMsg(){
            requireActivity().showSendMessageDialog("说点什么。。。"){
                val msg = this
                val entity = MsgEntity()
                val list: ArrayList<String> = ArrayList()
                list.add(MMKVConsts.liveUid)
                V2TIMManager.getInstance().getUsersInfo(list,object :V2TIMValueCallback<List<V2TIMUserFullInfo>>{
                    override fun onSuccess(p0: List<V2TIMUserFullInfo>?) {
                        Log.e("TAG", "onSuccess: ${p0?.get(0)?.customInfo}", )
                        entity.userName = p0?.get(0)?.nickName
                        entity.content = msg
                        entity.userId = MMKVConsts.liveUid
                        entity.type = MsgEntity.TYPE_NORMAL
                        showImMsg(entity)
                    }

                    override fun onError(p0: Int, p1: String?) {
                    }
                })

                senMsg(this){}
            }
        }
        fun sendGift(){
            liveRoomInfo?.apply {
                //避免显示多个 先清除下 也可写在别处
                users.clear()
                users.add(GiftUserInfo(userIcon = face,userId = live_uid,userDesc = pet_name))
                requireActivity().showSendGiftDialog(liveRoomInfo?.room_id!!,users){users, gift ->
                    var checkNum = 0
                    //只可以给主播一个人  不用循环
                    checkNum +=1
                    //消息回显
                    val list: ArrayList<String> = ArrayList()
                    list.add(MMKVConsts.liveUid)
                    V2TIMManager.getInstance().getUsersInfo(list,object :V2TIMValueCallback<List<V2TIMUserFullInfo>>{
                        override fun onSuccess(p0: List<V2TIMUserFullInfo>?) {
                            p0?.forEach {
                                val entity = MsgEntity()
                                entity.userName = p0[0].nickName
                                entity.content = "${MsgEntity.TYPE_GIFT}giftName#送 ${gift.name}  ×1"
                                entity.userId = MMKVConsts.liveUid
                                entity.type = MsgEntity.TYPE_NORMAL
                                showImMsg(entity)
                                senMsg(entity.content!!){}
                            }
                        }
                        override fun onError(p0: Int, p1: String?) {
                        }
                    })


                    //发送个礼物显示消息
                    senMsg("${MsgEntity.TYPE_GIFT}gift#${gift.img_type}#${if (gift.img_type == "0") gift.icon else gift.img}#${gift.time}"){
                        //发送event  让宿主显示动画
                        LiveEventBus.get<RoomGift>("RoomGift").post(gift)
                    }
                }
            }

        }
        fun sendGongNeng(){
            requireActivity().showLiveRoomManagerDialog(0){

            }
        }
    }

    /**
     * 发送礼物显示得消息
     */
    fun showImMsg(entity: MsgEntity) {
        runOnUiThread {

            adapter.addData( entity)
            bind?.revChat?.scrollToPosition(adapter.getItemCount() - 1);
//            if (mMsgEntityList.size > 1000) {
//                while (mMsgEntityList.size > 900) {
//                    mMsgEntityList.removeAt(0)
//                }
//            }
//            mMsgEntityList.add(entity)
//            mMsgListAdapter?.notifyDataSetChanged()
//            binding.rvImMsg.smoothScrollToPosition(mMsgListAdapter!!.itemCount)
        }
    }
}